import React, { Key, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  Tree,
  Card,
  Row,
  Col,
  Tag,
  Pagination,
  Table,
  Button,
  message,
} from "antd";
import {
  getHospitalDepartmentListRequest,
  getHosScheduleRuleRequest,
  findScheduleListRequest,
} from "@api/hospital/hospitalList";
import {
  hospitalDepartmentListType,
  bookingScheduleListType,
  findSCheduleListReturnType,
} from "@/api/hospital/model/hospitalListTypes";
export default function HospitalSchedule() {
  const navigate = useNavigate();
  const { hoscode } = useParams();

  //创建一个存储树形数据的状态，类型为返回的Schedule数据
  const [treeData, setTreeData] = useState<hospitalDepartmentListType>([]);
  //定义一个时间排班规则的当前页码
  const [page, setPage] = useState(1);
  //定义一个时间排班规则的每页条数
  const [limit, setLimit] = useState(3);
  //定义一个数据总数的类型
  const [total, setTotal] = useState(0);
  //定义当前选中的科室
  const [depCode, setDepCode] = useState("");
  //定义当前科室的排班规则
  const [scheduleRule, setScheduleRule] = useState<bookingScheduleListType>([]);
  //排班信息表格的状态
  const [sourceData, setSourceData] = useState<findSCheduleListReturnType>([]);
  //定义一个存储排班日期的状态
  const [workDate,setWorkDate]=useState('')
  //1.获取科室列表
  const getDepartmentList = async () => {
    const result = await getHospitalDepartmentListRequest(hoscode as string);
    // console.log(result);
    //将获取到的科室的数据交给state
    setTreeData(result);
    return result;
  };
  //2.获取时间表安排
  const getScheduleRule = async (
    pege: number,
    limit: number,
    depCode: string
  ) => {
    const result = await getHosScheduleRuleRequest({
      page,
      limit,
      hoscode: hoscode as string,
      depcode: depCode,
    });
    //设置时间排班列表
    setScheduleRule(result.bookingScheduleList);
    //定义一个数据总数的类型
    setTotal(result.total);
    setDepCode(depCode);
    // console.log(result);
    return result;
  };
  //3.通过时间列表获取人员列表数据
  const getFindScheduleList = async (workDate: string, depCode: string) => {
    const result = await findScheduleListRequest({
      hoscode: hoscode as string,
      depcode: depCode,
      workDate: workDate,
    });
    // console.log(result);
    setSourceData(result);
  };
  //初始化请求获取树形数据，并将其设置给状态
  useEffect(() => {
    const initData = async () => {
      const departmentList = await getDepartmentList();
      //对children类型断言，children的类型是联合类型可以为null,通过传递的方式将请求需要的参数传给子组件
      const initDepCode = (
        departmentList[0].children as hospitalDepartmentListType
      )[0].depcode;
      //将初始化的科室编号传递用来请求排班列表
      const scheduleRule = await getScheduleRule(page, limit, initDepCode);
      //获取排班的时间
      const initWorkDate = scheduleRule.bookingScheduleList[0].workDate;
      setWorkDate(initWorkDate)
      //将排班的时间传递，获取排班的人员列表
      await getFindScheduleList(initWorkDate, initDepCode);
    };
    //调用初始化数据的函数
    initData();
  }, []);

  //表格的字段
  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费（元）",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];
  //树形空间的样式
  const TreeStyle = {
    border: "1px solid #DDD",
    overflow: "auto",
    height: "480px",
  };
  //切换tree的事件回调函数
  const treeSelectHandle = async (depCodeArr: Key[]) => {
    if (depCodeArr.length === 0) { //完善多次点击同一项会继续发请求的细节
      return;
    }
    try {
      const depcode = depCodeArr[0] as string;
      //把当前的科室保存在状态中
      setDepCode(depcode);
      //根据点击的值 请求科室排班信息
      const scheduleRuleResult = await getScheduleRule(page, limit, depcode);
      //将第一项的排班时间，储存
      const firstWorkDate = scheduleRuleResult.bookingScheduleList[0].workDate;
      //根据第一个科室排班的信息 获取表格详细信息
      getFindScheduleList(firstWorkDate, depcode);
    } catch (error) {
      message.error("没有数据");
      //清空表格
      setSourceData([]);
    }
  };
  //点击选项的事件回调函数
  const scheduleRuleHandle = (workDate: string) => {
    return () => {
      setWorkDate(workDate);
       //发送详细请求
      getFindScheduleList(workDate, depCode);
    };
  };
  //改变页码的事件回调函数
  const changePageHandle = async (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);
    //将初始化的科室编号传递用来请求排班列表
    const scheduleRule = await getScheduleRule(page, limit, depCode);
    const firstWorkDate = scheduleRule.bookingScheduleList[0].workDate;
    setWorkDate(firstWorkDate)
    //将排班的时间传递，获取排班的人员列表
    getFindScheduleList(firstWorkDate, depCode);
  };
  return (
    <div>
      <Card>
        <p>选择:北京协和医院/多发性硬化专科门诊/2022-04-08</p>
        <Row gutter={20}>
          <Col span={5}>
            <Tree
            //树形空间的样式
              style={TreeStyle}
              //断言数据为数组，解决TS的报错，目前官方的解决方案
              treeData={treeData as []}
              //自定义数据字段名
              fieldNames={{ title: "depname", key: "depcode" }}
              //将树形控件的数据受控
              expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              //数据事件的选择事件
              onSelect={treeSelectHandle}
            />
          </Col>
          <Col span={19}>
            <div style={{ marginBottom: 20 }}>
              {/* 将获取到的时间表，拿去渲染 */}
              {scheduleRule.map((item) => {
                return (
                  <Tag
                    key={item.workDate}
                    color="green"
                    style={{ cursor: "pointer", background:workDate===item.workDate?'skyblue':''}}
                    onClick={scheduleRuleHandle(item.workDate)}
                  >
                    <p>{item.workDate}</p>
                    <p>
                      {item.availableNumber}/{item.reservedNumber}
                    </p>
                  </Tag>
                );
              })}
            </div>
            {/* 分页器组件 */}
            <Pagination
              current={page}
              pageSize={limit}
              total={total}
              onChange={changePageHandle}
            />
            <Table
              style={{ marginTop: 20 }}
              columns={columns}
              bordered
              dataSource={sourceData}
              pagination={false}
              rowKey={"id"}
            />
            <Button
              style={{ marginTop: 20 }}
              type="default"
              onClick={() => {
                navigate(-1);
              }}
            >
              返回
            </Button>
          </Col>
        </Row>
      </Card>
    </div>
  );
}
